package main

import (
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"strconv"
	"strings"
)

func main() {
	http.HandleFunc("/healthz", healthzHandler)
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal("ListenAndServe error:",err.Error())
	}
}

func healthzHandler(w http.ResponseWriter, r *http.Request) {
	header := r.Header
	// fmt.Println("request header:",header)
	var accept  string
	// 1、取header，map转字符串，写入response
	for _, v := range header["Accept-Language"] {
		accept += v
	}
	w.Header().Set("Accept-Language",accept)
	// 2、读取环境变量version
	os := os.Getenv("OS")
	// fmt.Println("os:",os)
	w.Header().Set("OS",os)
	// 3、获取clent IP
	ip,port,_ := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr))
	// 4、设置状态码200
	w.WriteHeader(http.StatusOK)

	fmt.Fprintf(w, "Hello "+r.URL.Path[1:]+"\n")
	fmt.Fprintf(w, "ip "+ip+"\n")
	fmt.Fprintf(w, "port "+port+"\n")
	fmt.Fprintf(w, "status code "+ strconv.Itoa(http.StatusOK)+"\n")
}
